package com.server.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.server.authority.Login;
import com.server.common.base.ProjectInfor;
import com.server.common.base.SessionData;
import com.server.service.IMsgManagementService;
import com.server.service.ISurveyPaperService;
import com.server.service.ISurveyTestService;
import com.server.web.DataVector;
import com.server.web.JSONSerielizer;
import com.server.web.OutputUtil;
import com.server.web.RequestInput;
import com.server.web.SessionUtil;

/** 
 * 试卷组装
 * @author wufeng
 * @date 创建时间：2016年7月20日 上午11:32:17 
 */
@Controller
@RequestMapping("surveyPaper")
public class SurveyPaperController {
	@Autowired 
	private ISurveyPaperService surveyPaperService;
	@Autowired 
	private IMsgManagementService msgManagementService;
	@Autowired 
	private ISurveyTestService surveyTestService;
    /**
    * 试卷列表页面
    * @author  作者 : wufeng
    * @date 创建时间：2016年8月12日 上午9:32:14 
    * @return  
    */
	@Login
    @RequestMapping("")
    public ModelAndView paperMv(){
    	ModelAndView mv = new ModelAndView("survey/paperList");
    	mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
    	return mv;
    }
    /**
    * 试卷列表数据
    * @author  作者 : wufeng
    * @date 创建时间：2016年8月13日 下午3:44:24 
    * @return  
    */
    @RequestMapping("listData/{state}")
    public void getList(HttpServletRequest request,
    		HttpServletResponse response,@PathVariable Integer state){
		String user = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
		String userType = SessionUtil.getStringAttri(request, SessionData.levelKey_mng);
    	DataVector<Map<String, Object>> listData =  surveyPaperService.
    			getList(userType,state, user, new RequestInput(request));
		OutputUtil.returnGridData(response, 
				listData.getCount(),JSONSerielizer.toJson(listData.getList(),null,null));
    }
    
    /**
    * 新增试卷
    * @author  作者 : wufeng
    * @date 创建时间：2016年8月15日 上午10:06:47 
    * @return  
    */
    @RequestMapping("addMv")
    public ModelAndView addMv(){
    	ModelAndView mv = new ModelAndView("survey/addPaper");
    	mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
    	return mv;
    }
    /**
    * 修改页面
    * @author  作者 : wufeng
    * @date 创建时间：2016年8月15日 下午4:42:43 
    * @return  
    */
    @RequestMapping("updateMv/{paperId}")
    public ModelAndView updateMv(@PathVariable Integer paperId){
    	ModelAndView mv = new ModelAndView("survey/addPaper");
    	mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
    	mv.addObject("paperId", paperId);
    	return mv;
    }
    /**
    * 试卷组装页面
    * @author  作者 : wufeng
    * @date 创建时间：2016年8月15日 上午11:46:33 
    * @return  
    */
    @RequestMapping("packages/{paperId}")
    public ModelAndView examMakeMv(@PathVariable String paperId){
    	ModelAndView mv = new ModelAndView("survey/surveyMaking");
    	mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
    	mv.addObject("paperId", paperId);
    	return mv;
    }
    /**
    * 新增问卷数据
    * @author  作者 : wufeng
    * @date 创建时间：2016年8月31日 下午2:43:12 
    * @return  
    */
    @RequestMapping("add")
    public void add(HttpServletRequest request, HttpServletResponse response){
    	String json = request.getParameter("data");
    	String user = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
    	Map<String, Object> map = JSONSerielizer.toMap(json);
    	Map<String, Object> reMap =  surveyPaperService.add(map, user);
    	String jsonMap = JSONSerielizer.toJson(reMap, null, null);
    	OutputUtil.returnString(response, jsonMap);
    	
    }
    /**
    * 修改试卷数据
    * @author  作者 : wufeng
    * @date 创建时间：2016年8月15日 下午4:48:14 
    * @return  
    */
    @RequestMapping("update/{paperId}")
    public void update(HttpServletRequest request, 
    		HttpServletResponse response, @PathVariable String paperId){
    	String json = request.getParameter("data");
    	String user = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
    	Map<String, Object> map = JSONSerielizer.toMap(json);
    	boolean isSuccess =  surveyPaperService.update(paperId, map, user);
    	OutputUtil.returnSuccess(response, isSuccess);
    }
    
   /**
    * 获取问卷数据
    * @author  作者 : wufeng
    * @date 创建时间：2016年8月15日 下午5:00:48 
    * @return  
    */
    @RequestMapping("map/{paperId}")
    public void getMapData(HttpServletRequest request,
    		HttpServletResponse response, @PathVariable Integer paperId){
    	Map<String, Object> map = surveyPaperService.getMap(paperId.toString());
    	String jsonString = JSONSerielizer.toJson(map, null, null);
    	OutputUtil.returnString(response, jsonString);
    }
    /**
    * 向试卷中添加试题
    * @author  作者 : wufeng
    * @date 创建时间：2016年8月17日 下午9:25:58 
    * @return  
    */
    @RequestMapping("addTest/{paperId}")
    public void addTest(HttpServletRequest request, HttpServletResponse response,
    		@PathVariable String paperId){
    	boolean isSuccess = true;
    	String user = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
    	String ids = request.getParameter("data");
    	String []id = ids.split(",");
    	for (String string : id) {
    		Map<String, Object> map = surveyTestService.getMap(string);
    		Object object = map.get("class_id");
    		if(!StringUtils.isEmpty(object)){
    			isSuccess = surveyPaperService.
    					addTestQuestions(paperId,string, object.toString(),user);
    		}
		}
    	OutputUtil.returnSuccess(response, isSuccess);
    }
    @RequestMapping("updatePaperTest/{paperId}")
    public void updatePaperTest(HttpServletRequest request, HttpServletResponse response,
    		@PathVariable String paperId){
    	boolean isSuccess = true;
    	String user = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
    	String ids = request.getParameter("data");
    	boolean success = true;
    	List<Map<String, Object>> list = surveyPaperService.list(paperId);
    	for (Map<String, Object> map : list) {
    		Object object = map.get("survey_res_id");
    		if(!StringUtils.isEmpty(object)){
    			int pos = ids.indexOf(object.toString());
    			if(pos < 0){
    				success = surveyPaperService.deleteTest(paperId,object.toString());
    			}else if(pos == 0){
    				if(ids.contains(",")){
    					ids = ids.replace(object.toString()+",", "");
    				}else {
    					ids = ids.replace(object.toString(), "");
					}
    			}else{
    				ids = ids.replace(","+object.toString(), "");
    			}
    		}
		}
    	if(ids == null||ids.length() < 0){
    		OutputUtil.returnSuccess(response, isSuccess);
    	}
    	String id[] = ids.split(",");
    	for (String string : id) {
    		Map<String, Object> map = surveyTestService.getMap(string);
    		Object object = map.get("class_id");
    		if(!StringUtils.isEmpty(object)&&success){
    			isSuccess = surveyPaperService.
    					addTestQuestions(paperId,string, object.toString(),user);
    		}
    	}
    	OutputUtil.returnSuccess(response, isSuccess);
    }
    
    /**
    * 配置用户
    * @author  作者 : wufeng
    * @date 创建时间：2016年8月15日 下午5:36:48 
    * @return  
    */
    @RequestMapping("paperSetup/{paperId}")
    public ModelAndView paperSetupMv(@PathVariable String paperId){
    	ModelAndView mv = new ModelAndView("survey/settingUser");
    	mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
    	mv.addObject("paperId", paperId);
    	return mv;
    }
    
    @RequestMapping("userlistMv")
    public ModelAndView userlistMv(){
    	ModelAndView mv = new ModelAndView("survey/userList");
    	mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
    	return mv;
    }
    @RequestMapping("userlist")
    public void userlist(HttpServletRequest request,
			HttpServletResponse response){
    	DataVector<Map<String, Object>> listData =  surveyPaperService.
    			getUserList(new RequestInput(request));
		OutputUtil.returnGridData(response, 
				listData.getCount(),JSONSerielizer.toJson(listData.getList(),null,null));
    }
    @RequestMapping("userData")
    public void userData(HttpServletRequest request,
    		HttpServletResponse response){
    	String str = request.getParameter("data");
		String []id = str.split(",");
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		for (String string : id) {
			Map<String, Object> map = new HashMap<String, Object>();
			map = surveyPaperService.getUserData(string);
			list.add(map);
		}
		String json = JSONSerielizer.toJson(list, null, null);
		OutputUtil.returnString(response, json);
    }
    
    /**
    * 问卷对象
    * @author  作者 : wufeng
    * @date 创建时间：2016年9月2日 下午3:41:13 
    * @return  
    */
    @RequestMapping("mapData/{paperId}")
    public void getMapData(HttpServletRequest request,
    		HttpServletResponse response,@PathVariable String paperId){
    	Map<String, Object> map = surveyPaperService.getMapData(paperId);
    	String json = JSONSerielizer.toJson(map, null, null);
		OutputUtil.returnString(response, json);
    }
    
    @RequestMapping("addObject/{paperId}")
    public void addObject(HttpServletRequest request,
    		HttpServletResponse response,@PathVariable String paperId){
    	String object = request.getParameter("data");
    	String uuid = request.getParameter("uuid");
    	boolean isSuccess = surveyPaperService.addObject(paperId, object,uuid);
    	OutputUtil.returnSuccess(response, isSuccess);
    }
    /**
    * 删除试卷
    * @author  作者 : wufeng
    * @date 创建时间：2016年8月15日 下午5:37:02 
    * @return  
    */
    @RequestMapping("delete")
	public void delete(HttpServletRequest request,
			HttpServletResponse response){
		boolean isSuccess = true;
		boolean isRight = true;
		String user = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
		String userType = SessionUtil.getStringAttri(request, SessionData.levelKey_mng);
		String str = request.getParameter("data");
		String []id = str.split(",");
		Map<String, Object> map = new HashMap<String, Object>();
		if(userType.equals("1")){
			for (String string : id) {
					isSuccess = surveyPaperService.delete(string);
			}
		}else {
			for (String string : id) {
				if(surveyPaperService.isRight(string, user)){
					isSuccess = surveyPaperService.delete(string);
				}else {
					isRight = false;
				}
			}
		}
		map.put("isSuccess", isSuccess);
		map.put("isRight", isRight);
		String mapJson = JSONSerielizer.toJson(map, null, null); 
		OutputUtil.returnString(response, mapJson);
	}
    
    /**
    * 选择问题页面
    * @author  作者 : wufeng
    * @date 创建时间：2016年8月16日 下午3:31:00 
    * @return  
    */
    @RequestMapping("questionListMv/{type}")
    public ModelAndView questionListMv(@PathVariable String type){
    	ModelAndView mv = new ModelAndView("survey/testSelectList");
    	mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
    	mv.addObject("type", type);
    	return mv;
    }
	/**
	* 选择试题列表数据
	* @author  作者 : wufeng
	* @date 创建时间：2016年8月15日 下午10:21:48 
	* @return  
	*/
	@RequestMapping("questionList/{type}")
	public void questionList(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String type){
		DataVector<Map<String, Object>> listData = surveyPaperService.getQuetionsList(type, new RequestInput(request));
		OutputUtil.returnGridData(response, listData.getCount(),JSONSerielizer.toJson(listData.getList(),null,null));
	}
	/**
	* 试题具体信息
	* @author  作者 : wufeng
	* @date 创建时间：2016年8月16日 下午3:32:22 
	* @return  
	*/
	@RequestMapping("questionListData")
	public void questionListData(HttpServletRequest request, 
			HttpServletResponse response){
		String id = request.getParameter("data");
		String arr[] = id.split(",");
		List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
		for (String string : arr) {
			Map<String, Object> map = surveyTestService.getMap(string);
			list.add(map);
		}
		String json = JSONSerielizer.toJson(list, null, null);
		OutputUtil.returnString(response, json);
	}
	
	/**
	* 继续编制试卷页面
	* @author  作者 : wufeng
	* @date 创建时间：2016年8月17日 下午3:07:37 
	* @return  
	*/
	@RequestMapping("makeMv/{paperId}")
	public ModelAndView makeMv(@PathVariable String paperId){
		ModelAndView mv = new ModelAndView("survey/addPaper");
    	mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
    	mv.addObject("paperId", paperId);
    	return mv;
		
	}
	
	/**
	* 试题ID列表
	* @author  作者 : wufeng
	* @date 创建时间：2016年8月17日 下午4:59:17 
	* @return  
	*/
	@RequestMapping("testList/{paperId}")
	public void testList(HttpServletRequest request, 
			HttpServletResponse response,@PathVariable String paperId){
		List<Map<String, Object>> list = surveyPaperService.getQuestionIdList(paperId);
		String reStr="";
		for (Map<String, Object> map : list) {
			Object obj = map.get("survey_res_id");
			if(!StringUtils.isEmpty(obj)){
				if(reStr == ""){
					reStr = obj.toString();
				}else{
					reStr +="," + obj.toString();
				}
			}
		}
		String json = JSONSerielizer.toJson(reStr, null, null);
		OutputUtil.returnString(response, json);
	}
	
	/**
	* 提交评估
	* @author  作者 : wufeng
	* @date 创建时间：2016年8月17日 下午9:27:20 
	* @return  
	*/
	@RequestMapping("submit")
	public void submit(HttpServletRequest request, 
			HttpServletResponse response){
		String str = request.getParameter("data");
		String user = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
		boolean isSuccess = true;
		Integer estimate = surveyPaperService.toEstimate(str, user);
		isSuccess = estimate > 0;
		OutputUtil.returnSuccess(response, isSuccess);
	}
	
	/**
	* 查看试卷
	* @author  作者 : wufeng
	* @date 创建时间：2016年8月17日 下午9:30:21 
	* @return  
	*/
	@RequestMapping("checkMv/{paperId}")
	public ModelAndView check(@PathVariable String paperId){
		ModelAndView mv = new ModelAndView("survey/paperInfo");
    	mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
    	mv.addObject("paperId", paperId);
    	return mv;
	}
	/**
	* 问卷分发
	* @author  作者 : wufeng
	* @date 创建时间：2016年9月5日 上午10:26:00 
	* @return  
	*/
	@RequestMapping("distributeMv/{paperId}")
	public ModelAndView distributeMv(@PathVariable String paperId){
		ModelAndView mv = new ModelAndView("survey/surveyDistribution");
		mv.addObject("rootPath", ProjectInfor.ROOT_PATH);
		mv.addObject("paperId", paperId);
		return mv;
	}
	
	/**
	* 分发
	* @author  作者 : wufeng
	* @date 创建时间：2016年9月5日 上午11:47:54 
	* @return  
	*/
	@RequestMapping("distribute/{paperId}")
	public void distribute(HttpServletRequest request, 
			HttpServletResponse response, @PathVariable String paperId){
		String user = SessionUtil.getStringAttri(request, SessionData.nameKey_mng);
		Map<String, Object> map = surveyPaperService.getMap(paperId);
		boolean isSuccess = true;
		Object obj = map.get("object");
		Object obj_uuid = map.get("object_uuid");
		String objStr = null;
		if(!StringUtils.isEmpty(obj)){
			objStr = obj.toString();
			if(!StringUtils.isEmpty(obj_uuid)){
				Map<String, Object> saveMap = new HashMap<String, Object>();
				Map<String, Object> inputMap = new HashMap<String, Object>();
				String user_uuid = obj_uuid.toString(); 
				String _user[] = user_uuid.split(",");
				List<String> users = new ArrayList<String>();
				for (String string : _user) {
					users.add(string);
				}
				inputMap.put("surveyId", paperId);
				int num = surveyPaperService.distribute(user, users, inputMap);
				String uuid = UUID.randomUUID().toString();
				saveMap.put("uuid", uuid);
				saveMap.put("type", "调研");
				saveMap.put("msgName", map.get("name"));
				saveMap.put("relatedId", paperId);
				Integer add = msgManagementService.add(user, users, saveMap);
				isSuccess = add > 0;
				if (isSuccess) {
					//放入内存等待推送
					Map<String, Object> reMap = new HashMap<String, Object>();
					reMap.put("pushTime", new Date());
					reMap.put("uuid", uuid);
					reMap.put("msgName", saveMap.get("msgName"));
					msgManagementService.addPrePushData(reMap);
				}
				
			}
		}
		surveyPaperService.change(paperId, "isDistribute", 1);
		OutputUtil.returnSuccess(response, isSuccess);
	}
}
